<?php

namespace frontend\models;

/**
 * @author  shuang
 * @date    2016-10-29 9:35:25
 * @version V1.0
 * @desc    
 */
use common\models\TaskReflesh;
use Yii;
use common\components\MTools;
use yii\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;
use common\models\Task;

class WB_TaskReflesh extends TaskReflesh {
    /*
     * 设置表操作行为动作
     * return array
     */

    public function behaviors() {
        return[
            [
                'class' => TimestampBehavior::className()
            ]
        ];
    }

    /*
     * 添加刷新任务
     * @params $taskid
     * @params $reno  刷新次数 default 1
     */

    public static function createTaskreflesh($taskid, $reno = 1, $auto = true) {
        $result = WB_TaskReflesh::find()->where("taskid=$taskid")->one();
        if (!$result instanceof WB_TaskReflesh) {
            $model = new WB_TaskReflesh();
            $model->taskid = $taskid;
            $model->reflash_count = $reno;
            $model->ref_pass = 1;
            $res = MTools::saveModel($model);
            if ($res === true) {
                $taskmodel = WB_Task::findOne($taskid);
                $taskmodel->reflash_at = time();
                return MTools::saveModel($taskmodel);
            }
        } else {
            if ($auto === true) {
                $taskmodel = WB_Task::findOne($taskid);
                $reflash_at = $taskmodel->reflash_at;
                $now = time();
                if ($now - (int) $reflash_at > 3600) {
                    $taskmodel->reflash_at = $now;
                    return $taskmodel->save();
                } else {
                    return ["errors" => ["taskid" => ["您的刷新时间还不够1小时，下次刷新时间" . date("Y-m-d H:i:s", $taskmodel->reflash_at + 3600) . "之后"]]];
                }
            } else {
                $result->reflash_count = $result->reflash_count + $reno;
                return $result->save();
            }
        }
    }

}
